<template>
  <div>
    <Form ref="formInline" :model="map" inline>
      <div class="search">
        <FormItem>
          <Input type="text" v-model="map.key" placeholder="关键字"></Input>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="getList">查询</Button>
        </FormItem>
      </div>
    </Form>
    <Tabs>
      <TabPane label="标签">
        <Form>
          <Tag v-for="tag in data.data" :key="tag.id" v-model="tag.id" :name="tag.id" type="border" closable
               color="primary"
               @on-close="removeTag">{{tag.title}}
          </Tag>
          <Input v-model="newTag" size="small" style="width: 100px;"></Input>
          <Button icon="ios-add" type="dashed" size="small" @click="addTag">添加标签</Button>
        </Form>
      </TabPane>
    </Tabs>
    <Page class="page" :total="data && data.count" :page-size="data && data.pagesize" show-total @on-change="changePage"></Page>

  </div>
</template>
<script>
  import {userTag} from "@/api";
  import {Button, Form, FormItem, Input, Option, Page, Select, Table, TabPane, Tabs, Tag,} from 'iview';

  export default {
    components: {
      Button,
      Table,
      Page,
      Form,
      FormItem,
      Input,
      Select,
      Option,
      Tag,
      Tabs,
      TabPane,
    },
    data() {
      return {
        loading: true,
        data: {},
        newTag: '',
        map: {
          page: 1,
          key: "",
          pageSize: 50,
        },
      };
    },
    methods: {
      getList() {
        this.loading = true;
        userTag.getList(this.map).then(res => {
          this.data = res.data;
          this.loading = false;
        });
      },

      changePage(index) {
        this.map.page = index;
        this.getList();
      },

      addTag() {
        const tag = this.newTag;
        if(tag) {
          let formData = {
            title: tag,
          };
          userTag.addTag(formData).then(res => {
            this.data.data.push({id: res.data, title: tag});
            this.newTag = '';
            //this.getList();
          });
        }
      },

      removeTag(event, name) {
        userTag.delete(name).then(res => {
          //避免重新加载
          const index = this.data.data.findIndex((tag) => {
            return tag.id === name;
          });
          this.data.data.splice(index, 1)
        });
      },
    },
    mounted() {
      this.getList();
    }
  };
</script>
